package com.prj.ufdm.file.dao._impl;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import com.prj.ufdm.file.dao.LocalStorFileDao;
import com.prj.ufdm.file.enums.UpFileRetCodeEnum;
import com.prj.ufdm.core.exception.BaseException;

@Repository
public class LocalStorFileDaoImpl implements LocalStorFileDao{

	@Value("${file.upload.dir}")
	private String uploadDir;
	@Value("${file.max.size:1M}")
	private String maxFileSize;
	@Value("${file.allow.type:*}")
	private String allowFileType;
	
	@Override
	public String saveFile(MultipartFile file) throws Exception {
		
		UUID uuid = UUID.randomUUID();
		String fileName = uuid.toString().replaceAll("-", "");
		String fileOriName = file.getOriginalFilename();
		int end = fileOriName.lastIndexOf(".");
		if(end < 0) {
			throw new BaseException(UpFileRetCodeEnum.RET_CODE_0401004.getCode(),UpFileRetCodeEnum.RET_CODE_0401004.getMessage());
		}
		String fileSuffix  = fileOriName.substring(end, fileOriName.length());
		if(file.getSize() > fileSize(maxFileSize)) {
			throw new BaseException(UpFileRetCodeEnum.RET_CODE_0401005.getCode(),UpFileRetCodeEnum.RET_CODE_0401005.getMessage());
		}
		List<String> result = Arrays.asList(allowFileType.split(","));
		boolean isFlag = false;
		for(String s : result) {
			if(s.toLowerCase().equals(fileSuffix.toLowerCase())) {
				isFlag = true;
			}
		}
		if(!isFlag) {
			throw new BaseException(UpFileRetCodeEnum.RET_CODE_0401006.getCode(),UpFileRetCodeEnum.RET_CODE_0401006.getMessage());
		}
		
		String uploadFilePathStr = createFileDir(uploadDir) + "/" + fileName + fileSuffix;
		
		Path uploadFilePath = Paths.get(uploadFilePathStr).toAbsolutePath().normalize();
		
		Files.copy(file.getInputStream(), uploadFilePath, StandardCopyOption.REPLACE_EXISTING);
		
		return uploadFilePathStr;
	}

	@Override
	public String getFile(String filePath) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public String createFileDir(String rootPath) throws Exception {
		Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
		int year = c.get(Calendar.YEAR); 
		int month = c.get(Calendar.MONTH)+1; 
		int date = c.get(Calendar.DATE); 
		String newFileDir = rootPath+"/"+year+"/"+month+"/"+date;
		File dateFile = new File(newFileDir);
		if (!dateFile.exists()) { 
			dateFile.mkdirs();
		}
		return newFileDir;
	}
	
	public static long fileSize(String fileSize) {
		long size = 0;
		if(fileSize.indexOf("GB") != -1) {
			String f = fileSize.replace("GB", "");
			size = Long.parseLong(f) * 1024 * 1024 * 1024;
		}else if(fileSize.indexOf("MB") != -1) {
			String f = fileSize.replace("MB", "");
			size = Long.parseLong(f) * 1024 * 1024;
		}else if(fileSize.indexOf("KB") != -1) {
			String f = fileSize.replace("KB", "");
			size = Long.parseLong(f) * 1024;
		}else if(fileSize.indexOf("B") != -1) {
			String f = fileSize.replace("B", "");
			size = Long.parseLong(f);
		}else {//默认KB
			size = Long.parseLong(fileSize) * 1024;
		}
		return size;
	}
}
